import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

// 取消注释这段代码，使用环境变量中设置的API基础URL
if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
  console.log('interceptor.ts: 环境变量中设置baseURL =', import.meta.env.VITE_API_BASE_URL);
} else {
  // 如果环境变量为空，则直接设置为8090端口
  axios.defaults.baseURL = 'http://localhost:8090';
  console.log('interceptor.ts: 环境变量为空，直接设置baseURL = http://localhost:8090');
}

// 注释掉这行代码
// axios.defaults.baseURL = '';
// console.log('interceptor.ts: 设置axios.defaults.baseURL为空，使用相对路径');

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 打印完整的请求URL
    const baseURL = config.baseURL || axios.defaults.baseURL || '';
    const url = config.url || '';
    console.log('完整请求URL:', `${baseURL}${url}`);
    
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    // 打印完整响应，便于调试
    console.log('响应数据:', response.data);
    
    const res = response.data;
    
    // 如果是登录接口，直接返回响应数据
    if (response.config.url?.includes('/api/user/login')) {
      return response;
    }
    
    // 检查响应格式，支持多种code值
    // 成功的code可能是20000或200
    if (res.code && res.code !== 20000 && res.code !== 200) {
      Message.error({
        content: res.msg || 'Error',
        duration: 5 * 1000,
      });

      // 处理401未授权的情况
      if (res.code === 401) {
        // 仅在非登录请求中处理
        if (!response.config.url?.includes('/api/user/info') && !response.config.url?.includes('/api/user/login')) {
          const userStore = useUserStore();
          userStore.logout();
          window.location.href = '/login';
        }
        return Promise.reject(new Error('未登录或登录已过期'));
      }

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        [50008, 50012, 50014].includes(res.code) &&
        response.config.url !== '/api/user/info'
      ) {
        Modal.error({
          title: 'Confirm logout',
          content:
            'You have been logged out, you can cancel to stay on this page, or log in again',
          okText: 'Re-Login',
          async onOk() {
            const userStore = useUserStore();
            await userStore.logout();
            window.location.reload();
          },
        });
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    return res;
  },
  (error) => {
    // 打印错误信息，便于调试
    console.error('响应错误详情:', error);
    
    // 处理401错误响应
    if (error.response && error.response.status === 401) {
      // 仅在非登录请求中处理
      if (!error.config.url?.includes('/api/user/info') && !error.config.url?.includes('/api/user/login')) {
        const userStore = useUserStore();
        userStore.logout();
        window.location.href = '/login';
      }
      return Promise.reject(new Error('未登录或登录已过期'));
    }
    
    Message.error({
      content: error.message || 'Request Error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
